﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;

namespace RedditWP.Reddit
{

    public delegate void RedditApiGetStringCallback(string response);        

    public class RedditApi
    {

        public void GetPageListing(string url, RedditApiGetStringCallback callback)
        {
            HttpGet(url, callback);
        }

        
        private void HttpGet(string url, RedditApiGetStringCallback callback) {
        
            
	       	WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(url), callback);
        
        }

        void  client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // completely artifical delay, to simulate real world mobile data
            Thread.Sleep(500);

            try
            {
                ((RedditApiGetStringCallback)e.UserState)(e.Result);
            }
            catch (WebException ex) 
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

        }

        /*
        // HttpWebRequest method
        private void HttpGet(string url, RedditApiGetStringCallback callback)
        {
            Uri uri = new Uri(url);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.BeginGetResponse(new AsyncCallback(HttpGetResponse), new RedditApiRequestState() { Callback = callback, Request = request}); 

        }

        private static void HttpGetResponse(IAsyncResult asynchronousResult) {
        
            RedditApiRequestState state = (RedditApiRequestState)asynchronousResult.AsyncState;

            HttpWebRequest request = state.Request;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

            StreamReader reader = new StreamReader(response.GetResponseStream());
            
            state.Callback(reader.ReadToEnd());
        }
        */

    } 

    class RedditApiRequestState 
    {
        
        public RedditApiGetStringCallback Callback {get; set;}
        public HttpWebRequest Request {get; set;}

    }
        

}
